import React, { useState } from 'react';
    import { useNavigate } from 'react-router-dom';
    import { useAuth } from '../../hooks/useAuth';
    import routes from '../../router/routeConfig';
    import './index.css';

    const ProfilePage = () => {
      const { user, updateUser, logout } = useAuth();
      const navigate = useNavigate();
      
      const [name, setName] = useState(user?.name || '');
      const [email, setEmail] = useState(user?.email || '');
      const [currentPassword, setCurrentPassword] = useState('');
      const [newPassword, setNewPassword] = useState('');
      const [confirmPassword, setConfirmPassword] = useState('');
      const [isLoading, setIsLoading] = useState(false);
      const [error, setError] = useState('');
      const [success, setSuccess] = useState('');
      const [activeTab, setActiveTab] = useState('profile'); // 'profile' or 'security'

      const handleProfileUpdate = async (e) => {
        e.preventDefault();
        
        if (!name) {
          setError('姓名不能为空');
          return;
        }
        
        setIsLoading(true);
        setError('');
        setSuccess('');
        
        try {
          // 在实际应用中，这里会调用API更新用户资料
          // const response = await api.put('/user/profile', { name, email });
          
          // 模拟API调用延迟
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          // 更新本地用户信息
          updateUser({ name, email });
          
          setSuccess('个人资料已成功更新');
        } catch (err) {
          setError('更新个人资料失败，请重试');
          console.error('更新个人资料错误:', err);
        } finally {
          setIsLoading(false);
        }
      };

      const handlePasswordChange = async (e) => {
        e.preventDefault();
        
        if (!currentPassword) {
          setError('请输入当前密码');
          return;
        }
        
        if (newPassword !== confirmPassword) {
          setError('两次输入的新密码不一致');
          return;
        }
        
        if (newPassword && newPassword.length < 6) {
          setError('新密码长度至少为6个字符');
          return;
        }
        
        setIsLoading(true);
        setError('');
        setSuccess('');
        
        try {
          // 在实际应用中，这里会调用API更改密码
          // const response = await api.put('/user/password', { currentPassword, newPassword });
          
          // 模拟API调用延迟
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          setSuccess('密码已成功更改');
          setCurrentPassword('');
          setNewPassword('');
          setConfirmPassword('');
        } catch (err) {
          setError('更改密码失败，请确认当前密码是否正确');
          console.error('更改密码错误:', err);
        } finally {
          setIsLoading(false);
        }
      };

      const handleLogout = () => {
        logout();
        navigate(routes.home);
      };

      return (
        <div className="container profile-page">
          <div className="profile-header">
            <h1><i className="fas fa-user-circle"></i> 个人资料</h1>
            <button onClick={handleLogout} className="logout-btn">
              <i className="fas fa-sign-out-alt"></i> 退出登录
            </button>
          </div>
          
          <div className="profile-content">
            <div className="profile-sidebar">
              <div className="user-info">
                <div className="avatar">
                  {user?.avatar ? (
                    <img src={user.avatar} alt={user.name} />
                  ) : (
                    <div className="avatar-placeholder">
                      {user?.name?.charAt(0) || '?'}
                    </div>
                  )}
                </div>
                <h3>{user?.name}</h3>
                <p>{user?.email}</p>
              </div>
              
              <div className="profile-tabs">
                <button 
                  className={`tab-btn ${activeTab === 'profile' ? 'active' : ''}`}
                  onClick={() => setActiveTab('profile')}
                >
                  <i className="fas fa-user"></i> 个人信息
                </button>
                <button 
                  className={`tab-btn ${activeTab === 'security' ? 'active' : ''}`}
                  onClick={() => setActiveTab('security')}
                >
                  <i className="fas fa-shield-alt"></i> 安全设置
                </button>
              </div>
            </div>
            
            <div className="profile-main">
              {error && (
                <div className="alert alert-error">
                  <i className="fas fa-exclamation-circle"></i> {error}
                </div>
              )}
              
              {success && (
                <div className="alert alert-success">
                  <i className="fas fa-check-circle"></i> {success}
                </div>
              )}
              
              {activeTab === 'profile' ? (
                <div className="profile-form-container">
                  <h2>个人信息</h2>
                  <form onSubmit={handleProfileUpdate} className="profile-form">
                    <div className="form-group">
                      <label htmlFor="name">姓名</label>
                      <input
                        type="text"
                        id="name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        placeholder="您的姓名"
                        required
                      />
                    </div>
                    
                    <div className="form-group">
                      <label htmlFor="email">电子邮箱</label>
                      <input
                        type="email"
                        id="email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        placeholder="您的电子邮箱"
                        required
                        disabled // 通常不允许更改邮箱，或需要特殊验证
                      />
                      <small>邮箱地址不可更改</small>
                    </div>
                    
                    <div className="form-actions">
                      <button 
                        type="submit" 
                        className="save-btn" 
                        disabled={isLoading}
                      >
                        {isLoading ? (
                          <>
                            <i className="fas fa-spinner fa-spin"></i> 保存中...
                          </>
                        ) : (
                          <>
                            <i className="fas fa-save"></i> 保存更改
                          </>
                        )}
                      </button>
                    </div>
                  </form>
                </div>
              ) : (
                <div className="profile-form-container">
                  <h2>安全设置</h2>
                  <form onSubmit={handlePasswordChange} className="profile-form">
                    <div className="form-group">
                      <label htmlFor="currentPassword">当前密码</label>
                      <input
                        type="password"
                        id="currentPassword"
                        value={currentPassword}
                        onChange={(e) => setCurrentPassword(e.target.value)}
                        placeholder="请输入当前密码"
                        required
                      />
                    </div>
                    
                    <div className="form-group">
                      <label htmlFor="newPassword">新密码</label>
                      <input
                        type="password"
                        id="newPassword"
                        value={newPassword}
                        onChange={(e) => setNewPassword(e.target.value)}
                        placeholder="请输入新密码（至少6个字符）"
                        required
                        minLength="6"
                      />
                    </div>
                    
                    <div className="form-group">
                      <label htmlFor="confirmPassword">确认新密码</label>
                      <input
                        type="password"
                        id="confirmPassword"
                        value={confirmPassword}
                        onChange={(e) => setConfirmPassword(e.target.value)}
                        placeholder="请再次输入新密码"
                        required
                      />
                    </div>
                    
                    <div className="form-actions">
                      <button 
                        type="submit" 
                        className="save-btn" 
                        disabled={isLoading}
                      >
                        {isLoading ? (
                          <>
                            <i className="fas fa-spinner fa-spin"></i> 更改中...
                          </>
                        ) : (
                          <>
                            <i className="fas fa-key"></i> 更改密码
                          </>
                        )}
                      </button>
                    </div>
                  </form>
                </div>
              )}
            </div>
          </div>
        </div>
      );
    };

    export default ProfilePage;
